/**
 * 
 */
package name.yzhu.wbdata.db;

import java.io.File;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.util.ConfigHelper;

import name.yzhu.common.EnvVariable;
import name.yzhu.common.conf.PropertyConfig;
import name.yzhu.database.DataBaseException;
import name.yzhu.database.DbSupport;
import name.yzhu.database.IDbUtil;
import name.yzhu.wbdata.db.model.User;

/**
 * @author yhzhu
 *
 */
public class DBUtil {
	static private final Log LOG = LogFactory.getLog(DBUtil.class);
	
	public static final String DEFAULT_SYSTEM_CFG_FILE
                        = name.yzhu.common.EnvVariable.getWorkingDirectory()
                        +File.separator+"conf"+File.separator+"wbdata.properties";


	private static final URL DEFAULT_CONFIG_FILE = ConfigHelper.locateConfig("hibernate.cfg.xml");


	private static final Long DEFAULT_ADMIN_UID = 1785784017L;

	private static final String ADMIN_UID_STR = "admin_uid";

	private static final String ACESS_TOKEN_STR = "access.token";
	
	private static DbSupport support = null;

	private static String adminAccessToken = null;
	private static PropertyConfig proCFG;
	
	public static void initialSystem() throws Exception {
		PropertyConfig cfg = new PropertyConfig();
		cfg.load(DBUtil.DEFAULT_SYSTEM_CFG_FILE);
		initialSystem(cfg);
	}
	
	public static void initialSystem(PropertyConfig cfg) throws Exception {
		EnvVariable.initialGlobalEnvVariable();
		proCFG = cfg;
		initialDatabase(cfg);
	}
	
	public static void destroy() {
		LOG.info("destroy begin...");
		if (support != null) {
			support.closeUtil();
			support.close();
		}
		LOG.info("destroy end...");
	}
	


	public static void initialDatabase(PropertyConfig cfg) throws DataBaseException{
		proCFG = cfg;
		initialDatabase();
	}
	
	public static void initialDatabase() throws DataBaseException{
		LOG.info("initialDatabase begin...");
		support = new DbSupport(DEFAULT_CONFIG_FILE, proCFG.getProperties());
		support.buildSessionFactory();
		queryAccessToken();
		if (adminAccessToken == null){
			adminAccessToken = proCFG.getString(ACESS_TOKEN_STR);
		}
		LOG.info("initialDatabase end");
	}
	
	private static void queryAccessToken() throws DataBaseException {
		IDbUtil db = getDbUtil();
		Long uid = proCFG.getLong(ADMIN_UID_STR, DEFAULT_ADMIN_UID);
		User u = db.getForObejct(User.class, uid);
		if (u != null)
		   adminAccessToken = u.getAccessToken();
	}

	public static IDbUtil getDbUtil(){
		return support.getDbUtil();
	}

	public static Session getDbSession(){
		return support.getStandaloneSession();
	}


	public static String getAdminAccessToken() {
		return adminAccessToken;
	}

}
